from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView

from rest_framework.response import Response
from itsdangerous import TimedJSONWebSignatureSerializer as  TJS

# Create your views here.
from rest_framework_jwt.settings import api_settings

from oauth import serializers
from oauth.models import OAuthQQUser


class QQLoginURLView(APIView):

    def get(self, request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'
        # 生成ＱＱ对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 调用ｕｒｌ方法生成url地址
        login_url = qq.get_qq_url()
        # 返回url地址
        return Response({'login_url': login_url})


class OauthView(CreateAPIView):
    # 获取序列化器
    serializer_class = serializers.Oauthserializers
    def get(self, request):
        # 取出前端传来code
        code = request.query_params.get('code')
        if code is None:
            return Response({'error': '缺少code值'}, status=400)
            # 根据code请求ｑｑ资源服务器获取access_token
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = qq.get_access_token(code)
        # 根据access_token请求ＱＱ资源服务器获取openid
        openid = qq.get_open_id(access_token)
        # 判断用户是否绑定帐号
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 没有绑定发送openid
            tjs = TJS(settings.SECRET_KEY, 300)
            data = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': data})
            # 如果绑定直接token发给前端
            # 生成jwt token
        else:
            # 获取用户对象
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            # 获取oauth_user关联的user
            return Response({

                'token': token,
                'username': user.username,
                'user_id': user.id
            })
